package com.dingreading.cloud.app.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dingreading.cloud.app.entity.StaffRoles;
import com.dingreading.cloud.app.entity.table.StaffRolesTableDef;
import com.dingreading.cloud.app.mapper.StaffRolesMapper;
import com.dingreading.cloud.app.service.StaffRolesService;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Row;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.dingreading.cloud.app.entity.table.StoresTableDef.stores;


/**
 * 服务层实现。
 *
 * @author Administrator
 * @since 2023-11-22
 */
@Service
public class StaffRolesServiceImpl extends BaseServiceImpl<StaffRolesMapper, StaffRoles, StaffRolesTableDef> implements StaffRolesService {

    @Override
    protected StaffRolesTableDef getTable() {
        return StaffRolesTableDef.staffRoles;
    }

    @Override
    public List<StaffRoles> getByStoreManager(String staffUid) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.staffUid.eq(staffUid))
                .and(table.enabled.eq(1))
                .and(table.roles.like(",50,"));

        return getMapper().selectListByCondition(condition);
    }

    @Override
    public List<JSONObject> getByStoreManagerList(String staffUid) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.staffUid.eq(staffUid))
                .and(table.enabled.eq(1))
                .and(table.roles.like(",50,"));

        QueryWrapper wrapper = QueryWrapper.create()
                .select(table.storeUid, stores.storeName)
                .from(table)
                .leftJoin(stores).on(table.storeUid.eq(stores.uid))
                .where(condition);

        List<Row> rows = getMapper().selectRowsByQuery(wrapper);

        List<JSONObject> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(rows)) {
            for (Row row : rows) {
                String storeUid = row.getString("store_uid");
                String storeName = row.getString("store_name");

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("storeUid", storeUid);
                jsonObject.put("storeName", storeName);
                list.add(jsonObject);
            }
        }
        return list;
    }

}
